package com.atliuzu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atliuzu.bean.TradePayBean;
import com.atliuzu.bean.TrafficBehaviorOfTheFunnelBean;
import com.atliuzu.utils.ClickHouseUtil;
import com.atliuzu.utils.DateFormatUtil;
import com.atliuzu.utils.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author w
 * @create 2022-08-21-21:11
 */
public class DwsTradePayWindow {
    public static void main(String[] args) throws Exception {
        //TODO 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment ( );
        env.setParallelism ( 1 );

        //TODO 2.状态后端设置
//        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60 * 1000L);
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
//        env.getCheckpointConfig().enableExternalizedCheckpoints(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
//        );
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(
//                3, Time.days(1), Time.minutes(1)
//        ));
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage(
//                "hdfs://hadoop102:8020/ck"
//        );
//        System.setProperty("HADOOP_USER_NAME", "atguigu");

        //TODO 3.读取DWD数据

        String payTopic = "dwd_trade_pay_detail_suc";
        String groupId = "Behavior_Of_The_Funnel";
        DataStreamSource<String> paySourceDS = env.addSource ( MyKafkaUtil.getFlinkKafkaConsumer ( payTopic, groupId ) );

        //TODO 5.按user_id聚合
        SingleOutputStreamOperator<JSONObject> payObjDS =
                paySourceDS.flatMap(new FlatMapFunction<String, JSONObject>() {
                    @Override
                    public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                        JSONObject jsonObject = JSONObject.parseObject(value);
                        out.collect(jsonObject);
                    }
                });
        KeyedStream<JSONObject, String> payKeyDS = payObjDS.keyBy ( json -> json.getString ( "user_id" ) );


        //TODO 6.去重，并将去重数据转化为Javabean对象

        SingleOutputStreamOperator<TradePayBean> payDS =

                payKeyDS.flatMap(new RichFlatMapFunction<JSONObject, TradePayBean>() {
                                       private ValueState<String> lastcartstate;

                                       @Override
                                       public void open(Configuration parameters) throws Exception {
                                           //设定ttl
                                           StateTtlConfig stateTtlConfig =
                                                   new StateTtlConfig.Builder(Time.days(1)).setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite).build();
                                           //创建状态描述器
                                           ValueStateDescriptor<String> descriptor = new ValueStateDescriptor<>("lastvalue", String.class);
                                           //将配置作用于状态描述器
                                           descriptor.enableTimeToLive(stateTtlConfig);
                                           //赋值状态
                                           lastcartstate=getRuntimeContext().getState(descriptor);
                                       }

                                       @Override
                                       public void flatMap(JSONObject value, Collector<TradePayBean> out) throws Exception {

                                           //获取状态
                                           String lastdate = lastcartstate.value();

                                           //获取日期
                                           String curDt = "";
                                           String updateTime = value.getString("callback_time");

                                           if (updateTime != null) {
                                               curDt = updateTime.split(" ")[0];
                                           } else {
                                               curDt = value.getString("create_time").split(" ")[0];
                                           }
                                           if (lastdate == null || !lastdate.equals(curDt)) {
                                               lastcartstate.update(curDt);
                                               Long ts = DateFormatUtil.toTs ( value.getString ( "create_time" ) ,true);
                                               out.collect ( new TradePayBean (
                                                       "",
                                                       "",
                                                       1L,
                                                       ts
                                               ) );
                                           }
                                       }
                                   }
                );



        //TODO 设置watermark
        SingleOutputStreamOperator<TradePayBean> watermarkDS = payDS.assignTimestampsAndWatermarks ( WatermarkStrategy.<TradePayBean>forBoundedOutOfOrderness ( Duration.ofSeconds ( 2 ) ).withTimestampAssigner ( new SerializableTimestampAssigner<TradePayBean> ( ) {
            @Override
            public long extractTimestamp(TradePayBean element, long recordTimestamp) {
                return element.getTs ( );
            }
        } ) );

        //todo 开窗聚合
        SingleOutputStreamOperator<TradePayBean> reduceDS = watermarkDS.windowAll ( TumblingEventTimeWindows.of ( org.apache.flink.streaming.api.windowing.time.Time.seconds ( 10L ) ) ).reduce ( new ReduceFunction<TradePayBean> ( ) {
            @Override
            public TradePayBean reduce(TradePayBean value1, TradePayBean value2) throws Exception {
                value1.setPayCt ( value1.getPayCt ( ) + value2.getPayCt ( ) );
                return value1;
            }
        }, new AllWindowFunction<TradePayBean, TradePayBean, TimeWindow> ( ) {
            @Override
            public void apply(TimeWindow window, Iterable<TradePayBean> values, Collector<TradePayBean> out) throws Exception {
                TradePayBean next = values.iterator ( ).next ( );
                //补充信息
                next.setTs ( System.currentTimeMillis ( ) );
                next.setEdt ( DateFormatUtil.toYmdHms ( window.getEnd ( ) ) );
                next.setStt ( DateFormatUtil.toYmdHms ( window.getStart ( ) ) );

                //输出数据
                out.collect ( next );
            }
        } );

        reduceDS.print ( "reduce>>>>>" );

        reduceDS.addSink( ClickHouseUtil.getJdbcSink("insert into dws_trade_pay_window values(?,?,?,?)"));

        //TODO 9.启动任务
        env.execute ( "DwsTrafficPageViewWindow" );
    }
}
